package com.situ.company.employee.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.company.employee.model.EmployeeModel;
import com.situ.company.employee.service.IEmployeeService;
import com.situ.company.employee.service.impl.EmployeeServiceImpl;
import com.situ.company.util.FmtRequest;
@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	} 
	
	private IEmployeeService service = new EmployeeServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String res = null;
		switch(req.getParameter("action")) {
		case "reg":
			res = reg(req);
			break;
		case "login":
			res = login(req);
			break;
		case "logout":
			req.getSession().removeAttribute("user");
			resp.sendRedirect(req.getContextPath() + "/web/login.jsp");
			return;
		}
		FmtRequest.write(resp.getWriter(), res);
	}

	private String login(HttpServletRequest req) {
		EmployeeModel model = FmtRequest.parseModel(req, EmployeeModel.class);
		String res=service.login(model);
		if("1".equals(res)) {
			req.getSession().setAttribute("user", service.selectModel(model));
		}
		return res;
	}

	private String reg(HttpServletRequest req) {
//		String code = req.getParameter("code");
//		String pass = req.getParameter("pass");
//		String name = req.getParameter("name");
//		EmployeeModel model = new EmployeeModel(code,name,pass);
		EmployeeModel model = FmtRequest.parseModel(req, EmployeeModel.class);
		return service.insert(model);
	}

}







